//
//  AppDelegate.m
//  BackgroundTaskSample
//
//  Created by moliya on 16/4/22.
//  Copyright © 2016年 Wanquan Network Technology. All rights reserved.
//

#import "AppDelegate.h"
#import "fetchViewController.h"
#import "taskViewController.h"
#import "transferViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    CGFloat sysVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (sysVersion >= 8.0f) { //iOS8 above
        if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
            [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
        }
    }
    
    //设置后台获取的间隔
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

#pragma mark - Background Task 多任务一：后台任务
- (void)applicationDidEnterBackground:(UIApplication *)application {
    UINavigationController *rootController = (UINavigationController *)self.window.rootViewController;
    taskViewController *taskController = (taskViewController *)rootController.topViewController;
    transferViewController *transferController = (transferViewController *)rootController.topViewController;
    if ([taskController respondsToSelector:@selector(executeBackgroundTask)]) {
        [taskController executeBackgroundTask];
    }else if ([transferController respondsToSelector:@selector(beginDownload)]) {
        [transferController beginDownload];
    }
}

#pragma mark - Background Fetch 多任务二：后台获取
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    UINavigationController *rootController = (UINavigationController *)self.window.rootViewController;
    fetchViewController *fetchController = (fetchViewController *)rootController.topViewController;
    if ([fetchController respondsToSelector:@selector(fetchDataWithCompletionHandler:)]) {
        [fetchController fetchDataWithCompletionHandler:^(CFBackgroundUpdateResult result) {
            NSLog(@"后台获取完成");
            switch (result) {
                case CFBackgroundUpdateResultNewData:
                    completionHandler(UIBackgroundFetchResultNewData);
                    break;
                case CFBackgroundUpdateResultNoData:
                    completionHandler(UIBackgroundFetchResultNoData);
                    break;
                case CFBackgroundUpdateResultFailed:
                    completionHandler(UIBackgroundFetchResultFailed);
                    break;
                default:
                    break;
            }
        }];
    }
}

#pragma mark - Background Transfer Service 多任务四：后台传输
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
    NSLog(@"处理后台传输");
    //调用后台传输完成回调，系统将会更新后台快照
    _backgroundSessionCompletionHandler = completionHandler;
    //此时可以弹出本地通知来提醒用户
    //TODO
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    application.applicationIconBadgeNumber = 0;
    //进入前台，更新界面
    UINavigationController *rootController = (UINavigationController *)self.window.rootViewController;
    taskViewController *taskController = (taskViewController *)rootController.topViewController;
    if ([taskController respondsToSelector:@selector(updateTaskStateLabel)]) {
        [taskController updateTaskStateLabel];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
